#include "BondDetailTab.h"
#include "BondDetailData.h"
#include "SMenuButton.h"
#include "../QbBondModule.h"
#include <include/CmdDefines.h>
#include "../StringResource.h"
#include "../BondUtility.h"
#include "DetailTipsData.h"
#include <bondlib/BondContainer.h>
#include <bondlib/BondDict.h>
#include <bondlib/QBIssuerInfo.h>
#include <bondlib/QBSwSectorInfo.h>
#include <bondlib/QBProviceInfo.h>
#include <qbtools/tools.h>
#include <uam/UserAccountManager.h>
#include <core/StyleMgr.h>
#include <core/ImageMgr.h>
#include <widgets/STips.h>
#include <QLabel>
#include <QHBoxLayout>
#include <QMouseEvent>
#include <QMenu>
#include "bondlib/QBBondCrmClause.h"
#include "bondlib/AdditionBondInfo.h"
#include <utility>
#include <QStylePainter>
#include <QMetaEnum>

BondDetailTab::BondDetailTab(QWidget* p, QSharedPointer<DetailData> data)
	: QWidget(p), m_data(data)
{
	connect(m_data.get(), &DetailData::bondChanged, this, &BondDetailTab::onBondChanged);

	QHBoxLayout* mainL = new QHBoxLayout(this);
	mainL->setContentsMargins(0, 0, 0, 0);
	mainL->setSpacing(4);
	setLayout(mainL);

	QHBoxLayout* l = new QHBoxLayout();
	l->setContentsMargins(0, 0, 0, 0);
	l->setSpacing(4);
	mainL->addLayout(l, 1);
	mainL->addStretch(1);

	m_labelFirst = new QLabel(tr("经纪商行情", "Detail"), this);
	m_labelFirst->setAlignment(Qt::AlignCenter);
	m_labelFirst->installEventFilter(this);

	l->addWidget(m_labelFirst);
	m_labelSecond = new QLabel(tr("CFETS行情", "Detail"), this);
	m_labelSecond->setAlignment(Qt::AlignCenter);
	m_labelSecond->installEventFilter(this);

	l->addWidget(m_labelSecond);

	if (strcmp(SSUserAccountManager::instance().GetPermission().GetValue(USER_PERMISSION_WEB_BONDDETAIL), "1") == 0)
	{
		m_btnF9 = new SMenuButton(this);
		m_btnF9->setCaption(tr("F9 深度详情"));
		m_btnF9->setFixedSize(128, 24);
		m_btnF9->setIndex(0);
		mainL->addWidget(m_btnF9);
		connect(m_btnF9, &SMenuButton::hovered, this, &BondDetailTab::onShowMenu);
		connect(m_btnF9, &SMenuButton::clicked, this, &BondDetailTab::onBtnClicked);
	}

	m_btnIssue  = new SMenuButton(this);
	m_btnIssue->setCaption(tr("发行人历史成交"));
	m_btnIssue->setFixedSize(108, 24);
	m_btnIssue->setIndex(1);
	connect(m_btnIssue, &SMenuButton::clicked, this, &BondDetailTab::onBtnClicked);
	mainL->addWidget(m_btnIssue);

	m_styleSheet = QString("QLabel{color:#%1;background-color:#%2;border:none;border-radius:2px;}"
		"QLabel[selected=\"true\"]{background-color:#%3;}"
		"QLabel[selected=\"false\"]:hover{background-color:#%4;}")
		.arg(StyleMgr::instance().color("TextNormal").rgb(), 0, 16)
		.arg(StyleMgr::instance().color("BasicPlate").rgb(), 0, 16)
		.arg(StyleMgr::instance().color("ButtonNormal").rgb(), 0, 16)
		.arg(StyleMgr::instance().color("Hover").rgb(), 0, 16);
	setStyleSheet(m_styleSheet);
	setMouseTracking(true);
}

void BondDetailTab::setSelIndex(int index)
{
	m_labelFirst->setProperty("selected", index == 0 ? "true" : "false");
	m_labelSecond->setProperty("selected", index == 0 ? "false" : "true");
	setStyleSheet(m_styleSheet);//重置才起效？！
}

bool BondDetailTab::eventFilter(QObject* watched, QEvent* event)
{
	if (event->type() == QEvent::MouseButtonPress)
	{
		QMouseEvent* me = static_cast<QMouseEvent*>(event);
		if (me->button() == Qt::LeftButton)
		{
			int selBroker = m_selBroker;
			if (watched == m_labelFirst)
			{
				m_labelFirst->setProperty("selected", "true");
				m_labelSecond->setProperty("selected", "false");
				selBroker = -1;
			}
			else
			{
				m_labelFirst->setProperty("selected", "false");
				m_labelSecond->setProperty("selected", "true");
				selBroker = m_labelSecond->property("broker").toInt();
			}
			if (selBroker != m_selBroker)
			{
				if (m_data)
				{
					m_data->setBondType(selBroker == NEW_DETAIL_CFETS_BROKER ? em_CFETS : selBroker == NEW_DETAIL_EXCHANGE_BROKER ? em_Exchange : em_Broker);
				}

				m_selBroker = selBroker;
				emit tabSelected(m_selBroker);

				setStyleSheet(m_styleSheet);//重置才起效？！
			}
		}
	}

	return QWidget::eventFilter(watched, event);
}

static QLabel* s_label = new QLabel();

static bool AddCalCellData(int nDate, const QString& strName, bool issuerPeriod, InfoCellData& cellData, int& index, std::map<int, InfoCellData>& cells)
{
	if (nDate > 0) {
		cellData.m_strName = strName;
		cellData.m_strValue = issuerPeriod ? "--" : SSTools::int2Time(nDate);
		cells.insert(std::make_pair(index++, cellData));
		return true;
	}
	return false;
}

static void beginBlock(const QString& title, QString& htmlStr)
{
	QString str;
	str = QString("<div class='value'>%1</div> <div style='margin-top:4px;margin-right:0px;margin-bottom:4px;margin-left:16px'>").arg(title);
	htmlStr.append(str);
}

void endBlock(QString& htmlStr)
{
	htmlStr.append("</div>");
}

void beginTable(QString& htmlStr)
{
	QString str = "<table style='border-spacing:0px 4px'>";
	htmlStr.append(str);
}

void endTable(QString& htmlStr)
{
	htmlStr.append("</table>");
}

void beginRow(QString& htmlStr)
{
	htmlStr.append("<tr>");
}

void endRow(QString& htmlStr)
{
	htmlStr.append("</tr>");
}

void addCell(QString& htmlStr, InfoCellData data, bool secondCol = false)
{
	QString nameCellStr = QString("<td class='key' width='68'>%1</td>").arg(data.m_strName);
	htmlStr.append(nameCellStr);

	QString valueStr = data.m_strValue;
	if (!data.m_strValueExp.isEmpty())
		valueStr = data.m_strValue + "(" + data.m_strValueExp + ")";

	QString valueCellStr;
	if (data.m_colspan > 1)
		valueCellStr = QString("<td class='value' colspan='%1'>%2</td>").arg(data.m_colspan).arg(valueStr);
	else
	{
		if (secondCol)
			valueCellStr = QString("<td class='value' width='96'>%1</td>").arg(valueStr);
		else
			valueCellStr = QString("<td class='value' width='110'>%1</td>").arg(valueStr);
	}

	htmlStr.append(valueCellStr);
}

static QString buildHtml(const CBondInfo& bondInfo, DetailTipsData* tipsData, int nid)
{
	QString htmlStr;

	//TODO ENGLISH
	//基本信息
	std::map<int, InfoCellData>  basicInfo;
	xBondSSInfoNew_c* m_pBondBaseInfo = static_cast<xBondSSInfoNew_c*>(tipsData->getData(bondInfo.GetCombBondKey(),detailModel_BondDetail));
	QString strValue;
	QStringList strArray;
	BondDict stDict;
	InfoCellData l_CellData;
	for (int nCol = 0; nCol < Cell_MiniMax; ++nCol) {
		strValue = l_CellData.m_strValueExp = "";
		l_CellData.m_strValue = "--";
		l_CellData.m_strName = NewStringTable::strSuperBSMiniTips(nCol);
		l_CellData.m_colspan = 1;
		if (!bondInfo.IsValidBond()) {
			l_CellData.m_strValue = strValue;
			if (nCol == Cell_MiniMunicipal) l_CellData.m_strValue = "";
			basicInfo.insert(std::make_pair(nCol, l_CellData));
			continue;
		}
		switch (nCol) {
		case Cell_MiniFullName: {//全称
			strValue = QString::fromLocal8Bit(bondInfo.GetBondName().c_str());
			l_CellData.m_colspan = 3;
			break;
		}
		case Cell_MiniType: {//类别
			strArray = QString::fromLocal8Bit(bondInfo.GetBondSubType()).split("|");
			strValue = "";
			for (int nZ = 0; nZ < strArray.size(); nZ++) {
				CBondDict::instance().GetBondDict("Bond_Subtype", strArray.at(nZ).toLocal8Bit(), stDict);
				strValue += QString::fromLocal8Bit(stDict.selective_content);
				if (nZ < strArray.size() - 1) {
					strValue += ",";
				}
			}
			l_CellData.m_colspan = 3;
			break;
		}
		case Cell_MiniDeadLine: { //债券期限
			strValue = QString::fromLocal8Bit(bondInfo.GetTermToMaturity());
			break;
		}
		case Cell_MiniOption: {//含权类型
			strArray = QString::fromLocal8Bit(bondInfo.GetOptionType()).split("|");
			strValue = "";
			for (int ns = 0; ns < strArray.size(); ns++) {
				CBondDict::instance().GetBondDict("Option_Type", strArray.at(ns).toLocal8Bit(), stDict);
				strValue += QString::fromLocal8Bit(stDict.selective_content);
				if (ns < strArray.size() - 1)	strValue += ",";
			}
			break;
		}
		case Cell_MiniCouponType: {//利率方式
			if (strcmp("FRN", bondInfo.GetCouponType()) == 0 && m_pBondBaseInfo && m_pBondBaseInfo->m_Maturity_Date > 0 &&
				m_pBondBaseInfo->m_Maturity_Date == m_pBondBaseInfo->m_Next_coupon_Date) {
				strValue = QObject::tr("固定利率(原浮)");//固定利率(原浮)
			}
			else {
				strValue = QString::fromLocal8Bit(bondInfo.GetCouponTypeName());
			}
			break;
		}
		case Cell_MiniBaseRateName: {//基础利率名
			if (m_pBondBaseInfo && strcmp(m_pBondBaseInfo->m_Coupon_Type, "FRN") == 0) {
				strValue = QString("%1 %2D").arg(QString::fromLocal8Bit(m_pBondBaseInfo->m_FRN_Index_ID)).arg(m_pBondBaseInfo->m_Fixing_MA_Days);
			}
			break;
		}
		case Cell_MiniSize: {//发行量
			std::set<int>* pSet = nullptr;
			CBondContainer& cont = CBondContainer::instance();
			cont.GetAdditionList(nid, pSet);
			double amount = bondInfo.GetActualIssueAmount();
			if (pSet) {
				for (std::set<int>::iterator itset = pSet->begin(); itset != pSet->end(); ++itset) {
					amount += cont.GetBond(*itset)->GetActualIssueAmount();
				}
			}
			if (amount >= 100) {
				strValue = QObject::tr("%1亿元").arg(amount / 10000.0, 0, 'f', 2);
			}
			break;
		}
		case Cell_MiniCouponRate: {//票面利率
			if (strcmp("DSC", bondInfo.GetCouponType()) == 0) //利率方式为贴现
			{
				l_CellData.m_strName = QObject::tr("发行收益");
				strValue = QString::fromLocal8Bit(bondInfo.GetIssueRate()) + "%";//票面利率显示发行收益
			}
			else if (strlen(bondInfo.GetCouponRateCurrent()) > 0) {
				strValue = BondUtility::FormatBidLimitTop(QString::fromLocal8Bit(bondInfo.GetCouponRateCurrent())) + "%";
			}
			break;
		}
		case Cell_MiniFrequency: {//计息频率
			if (strcmp(bondInfo.GetCompoundFrequency(), "N") != 0 && strcmp(bondInfo.GetCompoundFrequency(), "Null") != 0) {
				CBondDict::instance().GetBondDict("Compound_Frequency", bondInfo.GetCompoundFrequency(), stDict);
				strValue = QString::fromLocal8Bit(stDict.selective_content);
			}
			break;
		}
		case Cell_MiniMunicipal: {//是否城投
			strValue = "";
			if (bondInfo.GetIsMunicipal() == 'Y' || bondInfo.GetIsMunicipal() == 'y')	strValue = QObject::tr("是");
			else if (bondInfo.GetIsMunicipal() == 'N' || bondInfo.GetIsMunicipal() == 'n')	strValue = QObject::tr("否");
			break;
		}
		default:
			break;
		}
		if (nCol != Cell_MiniMunicipal && strValue.isEmpty())	strValue = "--";
		l_CellData.m_strValue = strValue;
		basicInfo.insert(std::make_pair(nCol, l_CellData));
	}

	//发行人信息
	std::map<int, InfoCellData>  issueInfo;
	xBondIssuerInfo_c* m_pBondInssueInfo = static_cast<xBondIssuerInfo_c*>(tipsData->getData(bondInfo.GetCombBondKey(), detailModel_PublisherBasic));
	QString strFirst = "", strSecond = "", strPArea = "";
	if (m_pBondInssueInfo) {
		auto pIssuer = CQBIssuerInfo::instance().GetIssuerInfo(m_pBondInssueInfo->m_IssuerCode);
		if (pIssuer) {
			const QBSWSECTORINFO* pSiFst = CQBSwSectorInfo::instance2021() .GetSwSectorInfo(pIssuer->field((int)kIssuerInfo::SW_2021_Sector_Code));
			if (pSiFst) {
				strFirst = QString::fromLocal8Bit(pSiFst->SW_Name);
			}
			const QBPROVINCEINFO* pArea = CQBProvinceInfo::instance().GetProviceInfo(pIssuer->field((int)kIssuerInfo::Province_Code));
			if (pArea) {
				strPArea= QString::fromLocal8Bit(pArea->Area_Name);
			}
		}
	}
	
	QString strValue2;
	int nIndex = 0;
	InfoCellData CellData;
	for (int nCol = 0; nCol < Cell_IsuMax; ++nCol) {
		strValue = strValue2 = "--";
		CellData.m_strName = NewStringTable::strSuperIsuTips(nCol);
		CellData.m_colspan = 1;
		if (!m_pBondInssueInfo) {
			CellData.m_strValue = strValue;
			if (nCol >= Cell_ControlShare && nCol != Cell_ShareRatio) CellData.m_strValueExp = strValue2;
			else CellData.m_strValueExp = "";
			issueInfo.insert(std::make_pair(nIndex, CellData));
			++nIndex;
			continue;
		}
		switch (nCol) {
		case Cell_Isu: { //发行人主体
			strValue = QString::fromLocal8Bit(m_pBondInssueInfo->m_Full_Name_C);
			CellData.m_colspan = 3;
			break;
		}
		case Cell_IsuType: {//主体类型
			if (m_pBondInssueInfo)
			{
				strValue = "";
				strArray = QString::fromLocal8Bit(m_pBondInssueInfo->m_Institution_Type).split(";");
				for (int i = 0; i < strArray.size(); i++) {
					CBondDict::instance().GetBondDict("Stakeholder_Type", strArray.at(i).toLocal8Bit(), stDict);
					strValue +=  QString::fromLocal8Bit(stDict.selective_content);
					if (i < strArray.size() - 1)	strValue += ",";
				}
			}
			
			break;
		}
		case Cell_FirstSector: {//一级行业
			strValue = strFirst;
			break;
		}
		case Cell_Province: {//地区（省）
			strValue = strPArea;
			break;
		}
		case Cell_ControlShare: {//控股股东
			if (m_pBondInssueInfo)
			{
				strValue = QString::fromLocal8Bit(m_pBondInssueInfo->m_Stockholder_name);
				strArray = QString::fromLocal8Bit(m_pBondInssueInfo->m_Stockholder_type).split(";");
				strValue2 = "";
				for (int i = 0; i < strArray.size(); i++) {
					CBondDict::instance().GetBondDict("Stakeholder_Type", strArray.at(i).toLocal8Bit(), stDict);
					strValue2 += QString::fromLocal8Bit(stDict.selective_content);
					if (i < strArray.size() - 1)	strValue2 += ",";
				}
				if (strValue2.isEmpty()) strValue2 = "--";
			}

			CellData.m_strValueExp = strValue2;
			CellData.m_colspan = 3;
			
			break;
		}
		case Cell_ShareRatio: {//控股比例
			if (m_pBondInssueInfo)
			{
				strValue = QString::fromLocal8Bit(m_pBondInssueInfo->m_Stockholding_percentage);
			}
			
			CellData.m_strValueExp = "";
			break;
		}
		case Cell_ActualControl: {//实际控制人
			if (m_pBondInssueInfo)
			{
				strValue = QString::fromLocal8Bit(m_pBondInssueInfo->m_Actual_Controller);
				strArray = QString::fromLocal8Bit(m_pBondInssueInfo->m_Actual_Controller_type).split(";");
				for (int i = 0; i < strArray.size(); i++) {
					CBondDict::instance().GetBondDict("Stakeholder_Type", strArray.at(i).toLocal8Bit(), stDict);
					strValue2 += QString::fromLocal8Bit(stDict.selective_content);
					if (i < strArray.size() - 1)	strValue2 += ",";
				}
			}
			
			if (strValue2.isEmpty()) strValue2 = "--";
			CellData.m_strValueExp = strValue2;// _T("实际控制人--类型"); 
			CellData.m_colspan = 3;
			break;
		}
		default: {	continue; }
		}
		if (strValue.isEmpty())	strValue = "--";
		CellData.m_strValue = strValue;
		issueInfo.insert(std::make_pair(nIndex, CellData));
		++nIndex;
	}

	//日历
	std::map<int, InfoCellData>  baseCalInfo;

	bool bIssuerPeriod = strlen(bondInfo.GetIssuePeriod()) > 0;
	nIndex = 0;
	AddCalCellData(atoi(bondInfo.GetIssueStartDate()), NewStringTable::strSuperCal(0), bIssuerPeriod, l_CellData, nIndex,baseCalInfo);//_T("发行开始日");
	AddCalCellData(atoi(bondInfo.GetAuctionDateStart()), NewStringTable::strSuperCal(1), bIssuerPeriod, l_CellData, nIndex, baseCalInfo);//_T("招标/建档日");
	AddCalCellData(atoi(bondInfo.GetInterestStartDate()), NewStringTable::strSuperCal(2), bIssuerPeriod, l_CellData, nIndex, baseCalInfo);//_T("起息日");
	AddCalCellData(atoi(bondInfo.GetPaymentDate()), NewStringTable::strSuperCal(3), bIssuerPeriod, l_CellData, nIndex, baseCalInfo);//缴款日
	AddCalCellData(atoi(bondInfo.GetListDate()), NewStringTable::strSuperCal(4), bIssuerPeriod, l_CellData, nIndex, baseCalInfo);//_T("上市日");
	if (m_pBondBaseInfo) AddCalCellData(m_pBondBaseInfo->m_Next_coupon_Date, NewStringTable::strSuperCal(5), bIssuerPeriod, l_CellData, nIndex, baseCalInfo);//_T("下次付息日");
	AddCalCellData(atoi(bondInfo.GetOptionDate()), NewStringTable::strSuperCal(6), bIssuerPeriod, l_CellData, nIndex, baseCalInfo);//_T("行权日");
	if (m_pBondBaseInfo)AddCalCellData(m_pBondBaseInfo->m_Delisted_Date, NewStringTable::strSuperCal(7), bIssuerPeriod, l_CellData, nIndex, baseCalInfo);//_T("下市日");
	AddCalCellData(atoi(bondInfo.GetMaturityDate()), NewStringTable::strSuperCal(8), bIssuerPeriod, l_CellData, nIndex, baseCalInfo);//_T("到期日");


	QColor txtKeyColor = StyleMgr::instance().color("TextNormal");
	QColor txtValueColor = StyleMgr::instance().color("Highlight");
	htmlStr = QString("<style>.value{color:#%1; vertical-align:top;padding-left:8px} .key{color:#%2; text-align:right;vertical-align:top; white-space:nowrap;} </style><div>")
		.arg(txtValueColor.rgb(), 0, 16).arg(txtKeyColor.rgb(), 0, 16);


	//基本信息
	beginBlock(QObject::tr("基本信息"), htmlStr);
	beginTable(htmlStr);
	beginRow(htmlStr);
	addCell(htmlStr, basicInfo[Cell_MiniFullName]);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicInfo[Cell_MiniType]);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicInfo[Cell_MiniDeadLine]);
	addCell(htmlStr, basicInfo[Cell_MiniSize], true);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicInfo[Cell_MiniOption]);
	addCell(htmlStr, basicInfo[Cell_MiniCouponRate], true);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicInfo[Cell_MiniCouponType]);
	addCell(htmlStr, basicInfo[Cell_MiniFrequency], true);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicInfo[Cell_MiniBaseRateName]);
	addCell(htmlStr, basicInfo[Cell_MiniMunicipal], true);
	endRow(htmlStr);

	endTable(htmlStr);
	endBlock(htmlStr);

	//发行人
	QColor hrColor = StyleMgr::instance().color("BasicBtn_Filter_Tittle");
	QString hrStr;
	hrStr = QString("<hr style='border-color:#%1;'/>").arg(hrColor.rgb(), 0, 16);
	htmlStr.append(hrStr);
	beginBlock(QObject::tr("发行人"), htmlStr);
	beginTable(htmlStr);
	beginRow(htmlStr);
	addCell(htmlStr, issueInfo[Cell_Isu]);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, issueInfo[Cell_IsuType]);
	addCell(htmlStr, issueInfo[Cell_Province], true);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, issueInfo[Cell_FirstSector]);
	addCell(htmlStr, issueInfo[Cell_ShareRatio], true);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, issueInfo[Cell_ControlShare]);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, issueInfo[Cell_ActualControl]);
	endRow(htmlStr);

	endTable(htmlStr);
	endBlock(htmlStr);

	//日历
	htmlStr.append(hrStr);
	beginBlock(QObject::tr("债券日历"), htmlStr);
	beginTable(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, baseCalInfo[0]);
	addCell(htmlStr, baseCalInfo[4]);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, baseCalInfo[1]);
	addCell(htmlStr, baseCalInfo[5]);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, baseCalInfo[2]);
	addCell(htmlStr, baseCalInfo[6]);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, baseCalInfo[3]);
	addCell(htmlStr, baseCalInfo[7]);
	endRow(htmlStr);

	endTable(htmlStr);
	endBlock(htmlStr);


	endBlock(htmlStr);
	return htmlStr;
}

static QString buildHtmlCrm(const CBondInfo& bondInfo, DetailTipsData* tipsData, int nid)
{
	QString htmlStr;
	//基本信息
	std::map<int, InfoCellData>  basicInfo;
	InfoCellData l_CellData;
	l_CellData.m_strValue = "--";
	xBondSSInfoNew_c* pBaseInfo = static_cast<xBondSSInfoNew_c*>(tipsData->getData(bondInfo.GetCombBondKey(), detailModel_BondDetail));

	QStringList strArray;
	BondDict stDict;
	const BOND_CRM_CLAUSE* crmCla = QBCRMBond::instance().GetBondByKey(bondInfo.GetBondKey());
	QString strValue, strTemp, strIssuer = "";
	if (crmCla) {
		strValue = QString::fromLocal8Bit(crmCla->CreaterCode.c_str());
		strArray = strValue.split("|");
		int nArrSz = strArray.size();
		if (nArrSz > 0) {
			//strIssuer1 = strArray[0];
			const IssuerInfo* pIssuer1 = CQBIssuerInfo::instance().GetIssuerInfo(std::string(strArray.at(0).toLocal8Bit()));
			if (pIssuer1) {
				strIssuer = QString::fromLocal8Bit(pIssuer1->field((int)kIssuerInfo::Full_Name_C));
			}
			if (nArrSz > 1) {
				//strIssuer2 = strArray[1];
				const IssuerInfo* pIssuer2 = CQBIssuerInfo::instance().GetIssuerInfo(std::string(strArray.at(1).toLocal8Bit()));
				if (pIssuer2) {
					strTemp = "\r\n" + QString::fromLocal8Bit(pIssuer2->field((int)kIssuerInfo::Full_Name_C));
					strIssuer = strIssuer + strTemp;
				}
			}
		}
	}
	//strIssuer = _T("中债信用增进投资股份有限公司\r\n中债信用增进投资股份有限公司");

	for (int nL = 0; nL < bas_Max; nL++) {
		l_CellData.m_strName = NewStringTable::strBDCrmBondInfo(nL);
		strValue = l_CellData.m_strValueExp = "";
		l_CellData.m_colspan = 1;
		switch (nL)
		{
		case bas_FullName: {//  债券全称
			l_CellData.m_colspan = 3;
			strValue = QString::fromLocal8Bit(bondInfo.GetBondName().c_str());
			break;
		}
		case bas_BondType: {//债券类别
			l_CellData.m_colspan = 3;
			strArray = QString::fromLocal8Bit(bondInfo.GetBondSubType()).split("|");
			for (int nZ = 0; nZ < strArray.size(); nZ++) {
				CBondDict::instance().GetBondDict("Bond_Subtype", strArray.at(nZ).toLocal8Bit(), stDict);
				strValue += QString::fromLocal8Bit(stDict.selective_content);
				if (nZ < strArray.size() - 1)	strValue += ",";
			}
			break;
		}
		case bas_Term: {//债券期限
			strValue = QString::fromLocal8Bit(bondInfo.GetTermToMaturity());
			break;
		}
		case bas_Price: {//信用保护费费率
			if (pBaseInfo) {
				double dbPrice = pBaseInfo->m_Issue_Price;
				if (bondInfo.IsAddIssueBond())
					dbPrice = (const_cast<CAdditionBondInfo*>(bondInfo.GetAdditionInfo()))->GetAddIssuePrice();
				if (dbPrice > 0.0001) {
					QString strTemp = QString::number(dbPrice, 'f', 4);
					strTemp = SSTools::PriceRemoveZero(strTemp, 1);
					strValue = strTemp + "%";
				}
			}
			break;
		}
		case bas_PlanAmount: {//计划创设额
			double dbVolumn = bondInfo.GetPlannedIssueAmount();
			if (dbVolumn > 0) {
				strValue = QString("%1万元").arg(dbVolumn, 0, 'f', 0);
			}
			break;
		}
		case bas_FirstAmount: {//预配售额
			if (crmCla && crmCla->FirstIssueAmount > 0) {
				strValue = QString("%1万元").arg(crmCla->FirstIssueAmount, 0, 'f', 0);
			}
			break;
		}
		case bas_SetModes: {//结算方式
			if (crmCla) {
				strValue = QString::fromLocal8Bit(crmCla->SettlementModes);
			}
			break;
		}
		case bas_Event: {//信用事件
			l_CellData.m_colspan = 3;
			if (crmCla) {
				strValue = QString::fromLocal8Bit(crmCla->CreditEvent.c_str());
			}
			break;
		}
		case bas_Issuer: {//创设机构1
			strValue = strIssuer;
			break;
		}
		default: {break; }
		}
		//static int nStTestEvent = 0;
		//if (nStTestEvent > 0 && nL == bas_Event){
		//	strValue = _T("债信用增进投资股份有限债信用增进投资股份有限债信用增进投资股份有限债信用增进投资股份有限");
		//}
		if (strValue.isEmpty()) strValue = "--";
		l_CellData.m_strValue = strValue;
		basicInfo.insert(std::make_pair(nL, l_CellData));
	}

	//参考信息
	std::map<int, InfoCellData>  refInfo;
	l_CellData.m_strValue = "--";

	xBondIssuerInfo_c* m_pBondInssueInfo = static_cast<xBondIssuerInfo_c*>(tipsData->getData(bondInfo.GetCombBondKey(), detailModel_PublisherBasic));
	bool bShowExtra = false;
	if (strcmp(bondInfo.GetBondSubType(), "CRM") == 0 || strcmp(bondInfo.GetBondSubType(), "crm") == 0) {
		bShowExtra = true;
	}
	const IssuerInfo* pReferIssuer = crmCla ? CQBIssuerInfo::instance().GetIssuerInfo(crmCla->ReferenceCode) : nullptr;
	CBondInfo* pRefBondInfo = nullptr;
	if (bShowExtra && crmCla) {
		pRefBondInfo = CBondContainer::instance().GetBond(crmCla->ReferBondKey);
	}
	for (int nL = 0; nL < ref_Max; nL++) {
		if (!bShowExtra && nL >= ref_refBond) continue;
		l_CellData.m_strName = NewStringTable::strBDCrmBondIssuer(nL);
		l_CellData.m_colspan = 1;
		strValue = l_CellData.m_strValueExp = "";
		switch (nL)
		{
		case ref_reference: {	//参考实体
			l_CellData.m_colspan = 3;
			if (crmCla && strlen(crmCla->ReferenceCode) > 0) {
				if (pReferIssuer) {
					strValue = QString::fromLocal8Bit(pReferIssuer->field((int)kIssuerInfo::Full_Name_C));
				}
			}
			break;
		}
		case ref_InstType: {			//机构类型
			if (pReferIssuer && strlen(pReferIssuer->field((int)kIssuerInfo::Issuer_Type)) > 0) {
				strArray = QString::fromLocal8Bit(pReferIssuer->field((int)kIssuerInfo::Issuer_Type)).split(";");
				strValue = "";
				for (int i = 0; i < strArray.size(); i++) {
					CBondDict::instance().GetBondDict("Stakeholder_Type", strArray.at(i).toLocal8Bit(), stDict);
					strValue += QString::fromLocal8Bit(stDict.selective_content);
					if (i < strArray.size() - 1)	strValue += ",";
				}
			}
			break;
		}
		case ref_FirSector: {			//一级行业 
			if (pReferIssuer && strlen(pReferIssuer->field((int)kIssuerInfo::SW_2021_Sector_Code)) > 0) {
				const QBSWSECTORINFO* pSi = CQBSwSectorInfo::instance2021().GetSwSectorInfo(pReferIssuer->field((int)kIssuerInfo::SW_2021_Sector_Code));
				if (pSi) {
					strValue = QString::fromLocal8Bit(pSi->SW_Name);
				}
			}
			break;
		}
		case ref_SecSector: {		//二级行业 
			if (pReferIssuer && strlen(pReferIssuer->field((int)kIssuerInfo::SW_2021_Subsector_Code)) > 0) {
				const QBSWSECTORINFO* pSi = CQBSwSectorInfo::instance2021().GetSwSectorInfo(pReferIssuer->field((int)kIssuerInfo::SW_2021_Subsector_Code));
				if (pSi) {
					strValue = QString::fromLocal8Bit(pSi->SW_Name);
				}
			}
			break;
		}
		case ref_City: {				//地区(省) 
			if (pReferIssuer && strlen(pReferIssuer->field((int)kIssuerInfo::Province_Code)) > 0) {
				const QBPROVINCEINFO* pArea = CQBProvinceInfo::instance().GetProviceInfo(pReferIssuer->field((int)kIssuerInfo::Province_Code));
				if (pArea != NULL) {
					strValue = QString::fromLocal8Bit(pArea->Area_Name);
				}
			}
			break;
		}
		case ref_ActualCon: {		//实际控制人 
			l_CellData.m_colspan = 3;
			if (pReferIssuer) {
				if (strlen(pReferIssuer->field((int)kIssuerInfo::Actual_Controller_Name)) > 0)
					strValue = QString::fromLocal8Bit(pReferIssuer->field((int)kIssuerInfo::Actual_Controller_Name));
				QString strValue2 = "";
				if (pReferIssuer->field((int)kIssuerInfo::Actual_Controller_Type)) {
					strArray = QString::fromLocal8Bit(pReferIssuer->field((int)kIssuerInfo::Actual_Controller_Type)).split(";");
					for (int i = 0; i < strArray.size(); i++) {
						CBondDict::instance().GetBondDict("Stakeholder_Type", strArray.at(i).toLocal8Bit(), stDict);
						strValue2 += QString::fromLocal8Bit(stDict.selective_content);
						if (i < strArray.size() - 1)	strValue2 += ",";
					}
					if (strValue2.isEmpty()) strValue2 = "--";
					l_CellData.m_strValueExp = strValue2;//
				}
			}
			break;
		}
		case ref_refBond: {			//参考债券 
			l_CellData.m_colspan = 3;
			if (pRefBondInfo && pRefBondInfo->IsValidBond()) {
				strValue = QString::fromLocal8Bit(pRefBondInfo->GetBondShortName());
			}
			break;
		}
		case ref_refType: {			//债券类别 
			l_CellData.m_colspan = 3;
			if (pRefBondInfo && pRefBondInfo->IsValidBond()) {
				strArray = QString::fromLocal8Bit(pRefBondInfo->GetBondSubType()).split("|");
				strValue = "";
				BondDict stDict;
				for (int nZ = 0; nZ < strArray.size(); nZ++) {
					CBondDict::instance().GetBondDict("Bond_Subtype", strArray.at(nZ).toLocal8Bit(), stDict);
					strValue += QString::fromLocal8Bit(stDict.selective_content);
					if (nZ < strArray.size() - 1)	strValue += ",";
				}
			}
			break;
		}
		case ref_refTerm: {			//债券期限 
			if (pRefBondInfo && pRefBondInfo->IsValidBond()) {
				strValue = QString::fromLocal8Bit(pRefBondInfo->GetTermToMaturity());
			}
			break;
		}
		case ref_refRate: {			//票面利率 
			if (pRefBondInfo && pRefBondInfo->IsValidBond() && strlen(pRefBondInfo->GetCouponRateCurrent()) > 0) {
				strValue = 
				strValue = BondUtility::FormatBidLimitTop(QString::fromLocal8Bit(pRefBondInfo->GetCouponRateCurrent())) + "%";
			}
			break;
		}
		case ref_refAmount: {		//发行量 
			if (pRefBondInfo && pRefBondInfo->IsValidBond()) {
				double dbAmount = pRefBondInfo->GetActualIssueAmount();
				if (dbAmount >= 100) {
					strValue = QObject::tr("%1亿元").arg(dbAmount / 10000.0, 0, 'f', 2);
				}
			}
			break;
		}
		default: {break; }
		}
		if (strValue.isEmpty()) strValue = "--";
		l_CellData.m_strValue = strValue;
		refInfo.insert(std::make_pair(nL, l_CellData));
	}

	//日历
	std::map<int, InfoCellData>  basicCalInfo;
	xBondSSInfoNew_c* m_pBondBaseInfo = static_cast<xBondSSInfoNew_c*>(tipsData->getData(bondInfo.GetCombBondKey(), detailModel_BondDetail));
	bool bIssuerPeriod = strlen(bondInfo.GetIssuePeriod()) > 0;
	int nRegisterDate = 0;
	if (crmCla) nRegisterDate = crmCla->RegistrationDate;
	//cal_Start = 0,//簿记建档日
	//	cal_Register,//凭证登记日
	//	cal_Listed,//上市日 
	//	cal_Delisted,//下市日 
	//	cal_Payment,//信用保护费支付日 
	//	cal_InterestStart,//信用保护起始日 
	//	cal_MaturityDate,//信用保护到期日 
	int nIndex = 0;
	AddCalCellData(atoi(bondInfo.GetAuctionDateStart()), NewStringTable::strBDCrmBondCal(0), bIssuerPeriod, l_CellData, nIndex, basicCalInfo);//cal_Start = 0,//簿记建档日
	AddCalCellData(nRegisterDate, NewStringTable::strBDCrmBondCal(1), bIssuerPeriod, l_CellData, nIndex, basicCalInfo);//cal_Register,//凭证登记日
	AddCalCellData(atoi(bondInfo.GetListDate()), NewStringTable::strBDCrmBondCal(2), bIssuerPeriod, l_CellData, nIndex, basicCalInfo);//_T("上市日");
	if (m_pBondBaseInfo)AddCalCellData(m_pBondBaseInfo->m_Delisted_Date, NewStringTable::strBDCrmBondCal(3), bIssuerPeriod, l_CellData, nIndex, basicCalInfo);//_T("下市日");
	AddCalCellData(atoi(bondInfo.GetPaymentDate()), NewStringTable::strBDCrmBondCal(4), bIssuerPeriod, l_CellData, nIndex, basicCalInfo); //信用保护费支付日 
	AddCalCellData(atoi(bondInfo.GetInterestStartDate()), NewStringTable::strBDCrmBondCal(5), bIssuerPeriod, l_CellData, nIndex, basicCalInfo);//_T("起息日");
	AddCalCellData(atoi(bondInfo.GetMaturityDate()), NewStringTable::strBDCrmBondCal(6), bIssuerPeriod, l_CellData, nIndex, basicCalInfo);//_T("信用保护到期日");

	QColor txtKeyColor = StyleMgr::instance().color("TextNormal");
	QColor txtValueColor = StyleMgr::instance().color("Highlight");
	htmlStr = QString("<style>.value{color:#%1; vertical-align:top;padding-left:8px} .key{color:#%2; text-align:right;vertical-align:top; white-space:nowrap;} </style><div>")
		.arg(txtValueColor.rgb(), 0, 16).arg(txtKeyColor.rgb(), 0, 16);


	//基本信息
	beginBlock(QObject::tr("基本信息"), htmlStr);
	beginTable(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicInfo[bas_FullName], false);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicInfo[bas_BondType], false);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicInfo[bas_Term], false);
	addCell(htmlStr, basicInfo[bas_PlanAmount], true);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicInfo[bas_Price], false);
	addCell(htmlStr, basicInfo[bas_FirstAmount], true);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicInfo[bas_Issuer], false);
	addCell(htmlStr, basicInfo[bas_SetModes], true);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicInfo[bas_Event], false);
	endRow(htmlStr);

	endTable(htmlStr);
	endBlock(htmlStr);

	//发行人
	QColor hrColor = StyleMgr::instance().color("BasicBtn_Filter_Tittle");
	QString hrStr;
	hrStr = QString("<hr style='border-color:#%1;'/>").arg(hrColor.rgb(), 0, 16);
	htmlStr.append(hrStr);

	beginBlock(QObject::tr("参考实体及债务"), htmlStr);
	beginTable(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, refInfo[ref_reference], false);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, refInfo[ref_InstType], false);
	addCell(htmlStr, refInfo[ref_FirSector], true);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, refInfo[ref_City], false);
	addCell(htmlStr, refInfo[ref_SecSector], true);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, refInfo[ref_ActualCon], false);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, refInfo[ref_refBond], false);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, refInfo[ref_refType], false);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, refInfo[ref_refTerm], false);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, refInfo[ref_refRate], false);
	addCell(htmlStr, refInfo[ref_refAmount], true);
	endRow(htmlStr);

	endTable(htmlStr);
	endBlock(htmlStr);

	//日历
	htmlStr.append(hrStr);
	beginBlock(QObject::tr("债券日历"), htmlStr);
	beginTable(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicCalInfo[cal_Start], false);
	addCell(htmlStr, basicCalInfo[cal_Payment], true);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicCalInfo[cal_Register], false);
	addCell(htmlStr, basicCalInfo[cal_InterestStart], true);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicCalInfo[cal_Listed], false);
	addCell(htmlStr, basicCalInfo[cal_MaturityDate], true);
	endRow(htmlStr);

	beginRow(htmlStr);
	addCell(htmlStr, basicCalInfo[cal_Delisted], false);
	endRow(htmlStr);

	endTable(htmlStr);
	endBlock(htmlStr);

	endBlock(htmlStr);
	return htmlStr;
}
void BondDetailTab::mouseMoveEvent(QMouseEvent* event)
{
	if (m_tipsRect.contains(event->pos()))
	{
		if (!m_tipsData)
		{
			m_tipsData = new DetailTipsData(this);
			connect(m_tipsData, &DetailTipsData::dataArrived, this, &BondDetailTab::showBasicInfo, Qt::QueuedConnection);
		}

		showBasicInfo("", detailModel_BondDetail);
	}
	else
		QBTips::hideTip();
}

void BondDetailTab::paintEvent(QPaintEvent* event)
{
	QColor bkClr = StyleMgr::instance().color("BasicPlate");
	int x = 0;
	if (m_showBasicInfo)
		x = m_showBoth ? m_labelSecond->frameGeometry().right() + 4 : m_labelFirst->frameGeometry().right() + 4;

	int right = m_btnF9 ? m_btnF9->frameGeometry().left() - 4 : m_btnIssue->frameGeometry().left() - 4;

	QStylePainter painter(this);
	QRect r = rect();
	r.setLeft(x);
	r.setRight(right);
	painter.setPen(Qt::NoPen);
	painter.setBrush(bkClr);
	painter.drawRoundedRect(r, 2, 2);

	if (m_showBasicInfo)
	{
		SImage* img = ImgMgr::instance().image("widgets_grid_reminder_prompt_c", WidgetStatus::kNormal, devicePixelRatioF());
		if (!img)
			return;

		x = right - 8 - img->width();
		int y = r.center().y() - img->height() / 2 + 1;
		painter.drawImage(x, y, *img);
		m_tipsRect.setRect(x, y, img->width(), img->height());

		x -= 4;
		r.setRight(x);
		painter.setPen(StyleMgr::instance().color("TextNormal"));
		painter.drawText(r, tr("基本要素"), QTextOption(Qt::AlignRight | Qt::AlignVCenter));
	}
}

void BondDetailTab::resizeEvent(QResizeEvent* event)
{
	QWidget::resizeEvent(event);
	resizeChildren();
}

void BondDetailTab::onBondChanged()
{
	if (atoi(m_data->bond().GetMarketType()) == 2)
	{
		m_showBasicInfo = true;
		m_labelFirst->show();
		m_labelSecond->hide();
		m_showBoth = false;
		if (strcmp(m_data->bond().GetListedMarket(), CBondContainer::lmCIB) == 0)
		{
			if (SSUserAccountManager::instance().GetCFETS_Permission())
			{
				m_labelSecond->setText(tr("CFETS行情", "Detail"));
				m_labelSecond->setProperty("broker", (char)NEW_DETAIL_CFETS_BROKER);
				m_labelSecond->show();
				m_showBoth = true;
			}
		}
		else if (SSUserAccountManager::instance().HasExchangeAuth(m_data->bond().GetListedMarket()))
		{
			m_labelSecond->setText(tr("交易所行情", "Detail"));
			m_labelSecond->setProperty("broker", (char)NEW_DETAIL_EXCHANGE_BROKER);
			m_labelSecond->show();
			m_showBoth = true;
		}

		//TODO:
		m_labelFirst->setProperty("selected", "true");
		m_labelSecond->setProperty("selected", "false");
		resizeChildren();
	}
	else
	{
		m_labelSecond->hide();
		m_labelFirst->hide();
		m_showBasicInfo = false;
	}
}

void BondDetailTab::onShowMenu(int index)
{
	if (index == 0)
	{
		QMenu* menu = new QMenu(this);
		menu->setAttribute(Qt::WA_DeleteOnClose);
		if (atoi(m_data->bond().GetMarketType()) == 2)
		{
            menu->addAction(tr("经纪商完整日内"), this, [=]() {onMenuClicked(BROKERDAILY); });
			if (m_data->bond().IsExchange())
                menu->addAction(tr("交易所行情"), this, [=]() {onMenuClicked(EXCHANGE); });
            menu->addAction(tr("历史行情"), this, [=]() {onMenuClicked(HISTORY); });
		}
        menu->addAction(tr("流动性"), this, [=]() {onMenuClicked(LIQUIDITYSCORE); });
        menu->addAction(tr("基本资料"), this, [=]() {onMenuClicked(PROFILE); });
        menu->addAction(tr("发行人"), this, [=]() {onMenuClicked(ISSUER); });
        menu->addAction(tr("相关债券"), this, [=]() {onMenuClicked(RELATED); });
        menu->addAction(tr("评级与事件"), this, [=]() {onMenuClicked(RATING); });
        menu->addAction(tr("估值"), this, [=]() {onMenuClicked(VALUATION); });

		if (!m_data->bond().is_interest_bond()) {
			if (!m_data->bond().CheckCommonUseType(CBondContainer::CommRailWay)) {
                menu->addAction(tr("信用利差"), this, [=]() {onMenuClicked(SPREAD); });
			}
		}

		QRect r = m_btnF9->frameGeometry();
		QPoint pos = mapToGlobal(r.bottomLeft());
		pos.setY(pos.y() + 2);
		menu->setFixedWidth(r.width());
		m_btnF9->showMenu(menu);
		menu->popup(pos);
	}
	
}

void BondDetailTab::onBtnClicked(int index)
{
	if (index == 0)
	{
		QString param = QString::fromLocal8Bit(m_data->bond().GetCombBondKey());
		param.append("|").append("PROFILE");

		QbBondModule::instance().app()->execCommand(CMD_WebBondDetail_Profile, param.toUtf8());
	}
	else if (index == 1)
	{
		QString param = "issuerCode=";
		param.append(m_data->bond().GetIssuerCode());

		QbBondModule::instance().app()->execCommand(CMD_IssuerInformation, param.toUtf8());
	}
}

void BondDetailTab::onMenuClicked(BondDetailTab::SUBPAGE_TYPE index)
{
    QMetaEnum meta_subpage = QMetaEnum::fromType<BondDetailTab::SUBPAGE_TYPE>();
    const char* key = meta_subpage.valueToKey(index);
    if (key == nullptr) {
        return;
    }
    const QString subpage = key;

	QString param = QString::fromLocal8Bit(m_data->bond().GetCombBondKey());
	param.append("|").append(subpage);

	QbBondModule::instance().app()->execCommand(CMD_WebBondDetail_Profile, param.toUtf8());
}

void BondDetailTab::showBasicInfo(QString bondkey, int type)
{
	if (!bondkey.isEmpty() && strcmp(bondkey.toLocal8Bit(), m_data->bond().GetCombBondKey()) != 0)
		return;

	int index = CBondContainer::instance().GetBondIndex(m_data->bond().GetCombBondKey());
	QString html = (m_data->crmType() == crm_crm || m_data->crmType() == crm_cln) ? buildHtmlCrm(m_data->bond(), m_tipsData, index) : buildHtml(m_data->bond(), m_tipsData, index);
	QBTips::showText(mapToGlobal(m_tipsRect.bottomLeft()), html, nullptr, nullptr, false, true,16);
}

void BondDetailTab::resizeChildren()
{
	int width = (rect().width() - 4) * 2 / 5;
	if(width < DETAIL_QUOTE_MIN_WIDTH)
		width = DETAIL_QUOTE_MIN_WIDTH;
	if (m_showBoth)
	{
		int width1 = (width - 4) / 2;
		m_labelFirst->setFixedWidth(width1);
		m_labelSecond->setFixedWidth(width - width1 - 4);
	}
	else
		m_labelFirst->setFixedWidth(width);
}
